package com.ppp.poi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ppp.poi.bean.base.BaseService;
import com.ppp.poi.bean.entity.User;
import com.ppp.poi.common.Parameter;
import com.ppp.poi.common.exception.AppSimpleException;
import com.ppp.poi.dao.UserDao;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Wu Jin
 * @create 2020-01-19
 */
@Slf4j
@Service
public class UserService extends BaseService<User, UserDao> {

  @Autowired
  private HttpService httpService;

  @Autowired
  private Parameter parameter;

  public User login(String code, String platform) {
    if (StringUtils.isBlank(platform)) {
      platform = "wechat";
    }
    switch (platform) {
      case "wechat":
      case "weixin":
        return wechatLogin(code);
      case "toutiao":
        return toutiaoLogin(code);
      default:
        return wechatLogin(code);
    }
  }

  public User wechatLogin(String code) {
    String wechatAuthUrl = String.format(parameter.getWechatLoginUrl(), code);
    JSONObject jsonObject = httpService.doGetForPojo(wechatAuthUrl, JSONObject.class);
    log.info(JSON.toJSONString(jsonObject));
    String openid = jsonObject.getString("openid");
    if (StringUtils.isBlank(openid)) {
      throw new AppSimpleException("登录失败");
    }
    String accessToken = jsonObject.getString("session_key");
    String unionid = jsonObject.getString("unionid");
    User user = dao.selectByOpenId(openid);
    if (null == user) {
      user = new User();
      user.setOpenId(openid);
      user.setUnionId(unionid);
      user.setPlatform("wechat");
      user.setAccessToken(accessToken);
    }
    String token = UUID.randomUUID().toString().replace("-", "");
    user.setToken(token);
    save(user);
    return user;
  }

  public User toutiaoLogin(String code) {
    String toutiaoAuthUrl = String.format(parameter.getToutiaoLoginUrl(), code);
    JSONObject jsonObject = httpService.doGetForPojo(toutiaoAuthUrl, JSONObject.class);
    log.info(JSON.toJSONString(jsonObject));
    String openid = jsonObject.getString("openid");
    if (StringUtils.isBlank(openid)) {
      throw new AppSimpleException("登录失败");
    }
    String accessToken = jsonObject.getString("session_key");
    User user = dao.selectByOpenId(openid);
    if (null == user) {
      user = new User();
      user.setOpenId(openid);
      user.setPlatform("toutiao");
      user.setAccessToken(accessToken);
    }
    String token = UUID.randomUUID().toString().replace("-", "");
    user.setToken(token);
    save(user);
    return user;
  }

  public User getByToken(String token) {
    return dao.selectByToken(token);
  }
}
